package com.zyf.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyf.common.lang.Result;
import com.zyf.pojo.Blog;
import com.zyf.service.BlogService;
import com.zyf.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张忆菲
 * @since 2020-09-11
 */
@RestController
public class BlogController {

    @Resource
    BlogService service;

    @GetMapping("/blogs")
    public Result findAll(@RequestParam(defaultValue = "1")  Integer page){
        //设置分页查询的条数和页码
        Page page1 = new Page(page,5);
        //倒序查询
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("created");
        IPage page2 = service.page(page1, wrapper);
        return Result.succ(page2);
    }

    @GetMapping("/blog/{id}")
    public Result findOne(@PathVariable("id") Long id){
        Blog byId = service.getById(id);
        Assert.notNull(byId,"该博客已经被删除");
        return Result.succ(byId);
    }

    @RequiresAuthentication
    @PostMapping("/blog/add")
    public Result add(@Validated @RequestBody Blog blog){
        Blog temp=null;
        //修改
        if(blog.getId()!=null){
            temp=service.getById(blog.getId());
            //只能修改自己的文章
            Assert.isTrue(temp.getUserId().longValue()== ShiroUtil.getprofile().getId().longValue(),"没有编辑权限");
        }else {
            //添加
            temp=new Blog();
            temp.setUserId(ShiroUtil.getprofile().getId());
            temp.setStatus(0);

        }

        BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
        service.saveOrUpdate(temp);

        return Result.succ(null);
    }


}

